package org.examples.javax.script;

import static org.junit.Assert.assertEquals;

import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.junit.Before;
import org.junit.Test;

public class ScriptEngineTest
{
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    private ScriptEngine scriptEngine;
    private StringWriter output;

    @Before
    public void initTestMethod()
    {
        List<ScriptEngineFactory> engineFactories = scriptEngineManager.getEngineFactories();
        ScriptEngineFactory rhinoEngineFactory = engineFactories.get(0);
        scriptEngine = rhinoEngineFactory.getScriptEngine();

        ScriptContext context = scriptEngine.getContext();
        output = new StringWriter();
        context.setWriter(new PrintWriter(output));
    }

    @Test
    public void testEvalString() throws ScriptException
    {
        scriptEngine.eval("print('Hello, World')");
        assertEquals("Hello, World", output.getBuffer().toString());
    }

    @Test
    public void testEvalStringBinidngs() throws ScriptException
    {
        Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.put("param1", 9);
        scriptEngine.eval("print('Passed param1 = ' + param1)", bindings);
        assertEquals("Passed param1 = 9", output.getBuffer().toString());
    }

    @Test
    public void testEvalReader() throws ScriptException
    {
        Reader reader = new StringReader("print('Hello, World')");
        scriptEngine.eval(reader);
        assertEquals("Hello, World", output.getBuffer().toString());
    }

}
